package com.lyh;

import com.google.gson.JsonObject;

import javax.swing.tree.DefaultMutableTreeNode;

/**
 * JSON树模型工具类
 */
public class JsonTreeModel {
    /**
     * 将树形结构转换为JSON对象
     * @param node 树形结构节点
     * @return JSON对象
     */
    public static JsonObject treeToJson(DefaultMutableTreeNode node) {
        JsonObject jsonObject = new JsonObject();
        buildJsonObject(jsonObject, node);
        return jsonObject;
    }

    private static void buildJsonObject(JsonObject jsonObject, DefaultMutableTreeNode node) {
        for (int i = 0; i < node.getChildCount(); i++) {
            DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) node.getChildAt(i);
            String key = childNode.toString();
            if (childNode.getChildCount() > 0) {
                JsonObject childObject = new JsonObject();
                buildJsonObject(childObject, childNode);
                jsonObject.add(key, childObject);
            } else {
                jsonObject.addProperty(key, key);
            }
        }
    }
}
